﻿/**********************************************************
 ●项目：Smartkernel
 ●公司：智能核心信息技术研发中心
 ●作者：曹艳白
 ●邮箱：caoyanbai@gmail.com
 ●创建：2008-08-10
 ●版本：1.0
**********************************************************/
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;
using Smartkernel.Exceptions;
using Smartkernel.Extensions;
using Smartkernel.Resource;

namespace Smartkernel.Caching
{
    /// <summary>
    /// ASP.NET本身的缓存实现机制，基于Cache的实现。提供按分类进行管理的缓存功能。
    /// </summary>
    public static partial class SmartAspnetCacher
    {
        #region 公有方法，属性和字段
        /// <summary>
        /// 加入永久缓存项
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">键</param>
        /// <param name="value">缓存项</param>
        public static void Add(string category, string key, object value)
        {
            if (value == null)
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_value_Null);
            }

            cache.Insert(CreateKey(category, key), value, null, Cache.NoAbsoluteExpiration, TimeSpan.Zero);
        }
        /// <summary>
        /// 加入默认分类永久缓存项
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">缓存项</param>
        public static void Add(string key, object value)
        {
            Add(defaultCategory, key, value);
        }
        /// <summary>
        /// 插入超时缓存项
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">键</param>
        /// <param name="value">缓存项</param>
        /// <param name="timeOut">超时时间</param>
        public static void Add(string category, string key, object value, TimeSpan timeOut)
        {
            if (value == null)
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_value_Null);
            }
            if (timeOut == null)
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_timeOut_Null);
            }
            if (timeOut.TotalMilliseconds <= 0)
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_timeOut_LessOrEqualZero);
            }

            cache.Insert(CreateKey(category, key), value, null, DateTime.Now.Add(timeOut), TimeSpan.Zero);
        }
        /// <summary>
        /// 插入默认分类超时缓存项
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">缓存项</param>
        /// <param name="timeOut">超时时间</param>
        public static void Add(string key, object value, TimeSpan timeOut)
        {
            Add(defaultCategory, key, value, timeOut);
        }
        /// <summary>
        /// 获取缓存项
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">键</param>
        /// <returns>缓存项</returns>
        public static object GetValue(string category, string key)
        {
            return cache[CreateKey(category, key)];
        }
        /// <summary>
        /// 获取默认分类缓存项
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>缓存项</returns>
        public static object GetValue(string key)
        {
            return GetValue(defaultCategory, key);
        }
        /// <summary>
        /// 判断缓存项是否存在
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">键</param>
        /// <returns>判断的结果，true表示存在，false表示不存在</returns>
        public static bool ContainsKey(string category, string key)
        {
            bool isContainsKey = false;
            key = CreateKey(category, key);
            if (cache[key] != null)
            {
                isContainsKey = true;
            }
            if (!isContainsKey)
            {
                //为了安全，删除缓存项为Null的缓存，认为缓存项为Null的缓存不存在
                cache.Remove(key);
            }
            return isContainsKey;
        }
        /// <summary>
        /// 判断默认分类缓存项是否存在
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>判断的结果，true表示存在，false表示不存在</returns>
        public static bool ContainsKey(string key)
        {
            return ContainsKey(defaultCategory, key);
        }
        /// <summary>
        /// 删除缓存项
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">键</param>
        public static void Remove(string category, string key)
        {
            cache.Remove(CreateKey(category, key));
        }
        /// <summary>
        /// 删除默认分类缓存项
        /// </summary>
        /// <param name="key">键</param>
        public static void Remove(string key)
        {
            Remove(defaultCategory, key);
        }
        /// <summary>
        /// 清空指定分类的全部缓存项
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        public static void Clear(string category)
        {
            if (category.IsNullOrEmptyOrBlank())
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_category_NullOrEmptyOrBlank);
            }

            if (cache.Count == 0)
            {
                //没有缓存项，直接返回
                return;
            }
            string start = category.Trim();
            lock (cache)
            {
                var enumerator = cache.GetEnumerator();
                List<string> list = new List<string>(cache.Count);
                string key = null;
                while (enumerator.MoveNext())
                {
                    key = enumerator.Key.ToString();
                    if (key.StartsWith(start))
                    {
                        //以所属分类作为开头的键符合清除条件
                        list.Add(key);
                    }
                }
                list.ForEach(item => cache.Remove(item));
            }
        }
        /// <summary>
        /// 清空默认分类的全部缓存项
        /// </summary>
        public static void Clear()
        {
            Clear(defaultCategory);
        }
        /// <summary>
        /// 清空全部分类缓存项
        /// </summary>
        public static void ClearAll()
        {
            if (cache.Count == 0)
            {
                //没有缓存项，直接返回
                return;
            }
            lock (cache)
            {
                List<string> list = new List<string>();
                var enumerator = cache.GetEnumerator();
                string key = null;
                while (enumerator.MoveNext())
                {
                    key = enumerator.Key.ToString();
                    list.Add(key);
                }
                list.ForEach(item => cache.Remove(item));
            }
        }
        #endregion
    }
    public static partial class SmartAspnetCacher
    {
        #region 私有方法，属性和字段
        /// <summary>
        /// 内部缓存器，基于ASP.NET的Cache实现
        /// </summary>
        private static Cache cache = HttpRuntime.Cache;
        /// <summary>
        /// 默认所属分类的名称
        /// </summary>
        private static string defaultCategory = "__SmartAspnetCacher__DefaultCategory";
        /// <summary>
        /// 根据分类和原始键产生实际存储的键
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">原始键</param>
        /// <returns>实际存储的键</returns>
        private static string CreateKey(string category, string key)
        {
            if (category.IsNullOrEmptyOrBlank())
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_category_NullOrEmptyOrBlank);
            }
            if (key.IsNullOrEmptyOrBlank())
            {
                throw new SmartException(SmartExceptionMessageResource.SmartAspnetCacher_key_NullOrEmptyOrBlank);
            }
            return category.Trim() + "__" + key.Trim().GetHashCode().ToString();
        }
        #endregion
    }
}
